package org.lzz.utils;


import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.sun.xml.bind.v2.TODO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 七牛云对象存储工具类
 *
 * @author xiaoss
 * @since 1.0, 2023年03月22日 12:05:27
 */
@Component
public class QiniuKodoUtil {

    // TODO:为啥此处的value注解不起作用
    // @Value("${qiniu.kodo.accessKey}")
    static String accessKey ="dUy_l4ZB7qdyI0Wwn-IkM4y4szhw9c7q8XFZAEw9";
    // @Value("${qiniu.kodo.secretKey}")
    static String secretKey ="mBLBh9ncKsZee4j7Vav3S-KlVfakTUgsbKuEKZMr";
    // @Value("${qiniu.kodo.bucket}")
    static String bucket = "lzz-big-event";
    // @Value("${qiniu.kodo.domain}")
    static String domain ="sv7o32s80.hn-bkt.clouddn.com";

    /**
     * 27      * 处理多文件
     * 28      * @param multipartFiles
     * 29      * @return
     * 30
     */
    public Map<String, List<String>> uploadImages(MultipartFile[] multipartFiles) {
        Map<String, List<String>> map = new HashMap<>();
        List<String> imageUrls = new ArrayList<>();
        for (MultipartFile file : multipartFiles) {
            imageUrls.add(uploadImageQiniu(file));
        }
        map.put("imageUrl", imageUrls);
        return map;
    }


    /**
     * 42      * 上传图片到七牛云
     * 43      * @param multipartFile
     * 44      * @return
     * 45
     */
    public static String uploadImageQiniu(MultipartFile multipartFile) {
        try {
            // 1、获取文件上传的流
            byte[] fileBytes = multipartFile.getBytes();
            // 2、创建日期目录分隔
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String datePath = dateFormat.format(new Date());

            // 3、获取文件名
            String originalFilename = multipartFile.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            // String filename = datePath+"/"+ UUID.randomUUID().toString().replace("-", "")+ suffix;

            // 4.构造一个带指定 Region 对象的配置类
            // Region.南(根据自己的对象空间的地址选
            Configuration cfg = new Configuration(Region.huanan());
            UploadManager uploadManager = new UploadManager(cfg);

            // 5.获取七牛云提供的 token
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            uploadManager.put(fileBytes, originalFilename, upToken);

            return domain + "/" + originalFilename;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


}

